package com.maltys.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * @author malty
 * @link <a href="https://leetcode.cn/problems/palindrome-partitioning/description/">分割回文串</a>
 */
public class PalindromePartition {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        backTracing(s, 0, new ArrayList<>(), res);
        return res;
    }

    private void backTracing(String s, int sIdx, List<String> buffer, List<List<String>> res) {
        if (sIdx == s.length()) {
            res.add(new ArrayList<>(buffer));
        }
        for (int i = sIdx; i < s.length(); i++) {
            String substring = s.substring(sIdx, i + 1);
            if (isPalindrome(substring)) {
                buffer.add(substring);
                backTracing(s, i + 1, buffer, res);
                buffer.remove(buffer.size() - 1);
            }
        }
    }

    private boolean isPalindrome(String origin) {
        int s = 0;
        int e = origin.length() - 1;
        while (s < e) {
            if (origin.charAt(s++) != (origin.charAt(e--))){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        PalindromePartition partition = new PalindromePartition();
        System.out.println(partition.partition("aab"));
    }
}
